//
//  PYTextInputLimitCount.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/5/28.
//

import Foundation

protocol PYInputView :UIView,UITextInput{
    
    var countOfLimit : Int{get set}
    
    var limitText : String? {get}
}

fileprivate var KEY_COUNTOFLIMIT = "keyForCountOfLimit"

extension PYInputView{
    
    var countOfLimit: Int {
        get {
            guard let count = objc_getAssociatedObject(self,&KEY_COUNTOFLIMIT) as? Int else {
                return 0
            }
           return count
        }
        set{
            objc_setAssociatedObject(self, &KEY_COUNTOFLIMIT, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func inputViewDidChange() -> Bool{
        
        let inputView = self
        
        guard inputView.markedTextRange == nil else {
            return true
        }
        guard let text = self.limitText else {
            return true
        }
        guard text.length > self.countOfLimit else {
            return true
        }
        let replaceText = text.subString(to: self.countOfLimit)
        guard let range = inputView.textRange(from: inputView.beginningOfDocument, to: inputView.endOfDocument) else {
            return true
        }
        inputView.replace(range, withText: replaceText)
        PYToast.toast("输入字数过长,最多输入\(self.countOfLimit)个字符")
        return false
    }
}
/*
 代理调用
 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{
 
    return  textView.inputViewDidChange()
 }
 */
extension UITextView : PYInputView{
    
    var limitText : String?{
        get{
            return self.text
        }
    }
}
/*
 代理调用
 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
 
    return  textField.inputViewDidChange()
 }
 */
extension UITextField : PYInputView{
    
    var limitText : String?{
        get{
            return self.text
        }
    }
}
